package com.example.test001.web;


import com.example.test001.build.shiro.commons.ShiroUtils;
import com.example.test001.build.shiro.realm.MyRealm;
import com.example.test001.model.OnLineUser;
import com.example.test001.model.User;
import com.example.test001.service.UserService;
import lombok.extern.slf4j.Slf4j;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.eis.SessionDAO;
import org.apache.shiro.subject.SimplePrincipalCollection;
import org.apache.shiro.subject.Subject;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.servlet.ModelAndView;




import java.util.Collection;
import java.util.List;
import java.util.Set;

@Slf4j
@RequiresRoles("admin")
@Controller
public class AdminController {



    @Autowired
    UserService userService;

    @Autowired
    SessionDAO sessionDAO;

    @Autowired
    Realm realm;


    @GetMapping("/getOnLine")
    public ModelAndView getAllOnLine() {


        Collection<Session> sessions = sessionDAO.getActiveSessions();



        List<OnLineUser> onLineUsers = ShiroUtils.OnlineUser(sessions);


        ModelAndView modelAndView = new ModelAndView();

        modelAndView.setViewName("online");

        modelAndView.addObject("online", onLineUsers);

        return modelAndView;

    }


    @GetMapping("/mandatory/{id}")
    public void mandatory(@PathVariable("id") Integer id) {


        System.out.println(id);

        User user = userService.selectUserByUID(id);

        String username = user.getUsername();

        ShiroUtils.mandatory(sessionDAO.getActiveSessions(),username);

        reloadAuthorizing((MyRealm) realm,username);



    }

    public static void reloadAuthorizing(MyRealm myRealm,String username) {


        Subject subject = SecurityUtils.getSubject();

        String realmName = subject.getPrincipals().getRealmNames().iterator().next();



        //第一个参数为用户名,第二个参数为realmName,test想要操作权限的用户
        SimplePrincipalCollection principals = new SimplePrincipalCollection(username, realmName);


        subject.runAs(principals);


        Cache<Object, org.apache.shiro.authc.AuthenticationInfo> cache2 = myRealm.getAuthenticationCache();



        Set<Object> set2 =  cache2.keys();


        cache2.remove(username);


        log.info("移除");






        Cache<Object,AuthorizationInfo> cache = myRealm.getAuthorizationCache();

        Set<Object> set =  cache.keys();

        for (Object obj: set) {

            log.info("权限key+"+obj.toString());
        }


        cache.remove(username);

        subject.releaseRunAs();
    }
}
